<template>
  <section class="template-categorylist">
    <h3 class="head">分类</h3>
    <ul>
      <li :class="['category-item',{'is-active':category.visible}]" v-for="(category,cIndex) in categoryList" :key="cIndex" @click="onShowBook(category,cIndex)">
        <el-popover placement="right-start" :title="category.name+'列表'" width="400" trigger="manual" v-model="category.visible">
          <div class="book-list">
            <el-table :data="bookList" v-loading="isBookListLoading" :show-header="false" class="book-table" style="width: 100%" v-if="bookList!=null && bookList.length>0">
              <el-table-column width="70" align="left">
                <template slot-scope="scope">
                  <img :src="scope.row.cover" class="book-img" />
                </template>
              </el-table-column>
              <el-table-column align="left">
                <template slot-scope="scope">
                  <p class="book-tit">{{scope.row.title}}</p>
                  <p class="book-author">{{scope.row.author}}</p>
                </template>
              </el-table-column>
              <el-table-column width="120" align="center">
                <template slot-scope="scope">
                  <span class="book-sort">排序:</span>
                  <el-input-number size="mini" style="width:50px" v-model="scope.row.showOrder" :controls="false" :min="1" :max="99" @change="onBookSortChange(scope.row)"></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="clearfix" slot="reference" @click="category.visible = !category.visible">
            <el-col :span="9">
              <div class="category-img-box">
                <el-upload class="category-uploader" @click.native.stop="onUpClick(cIndex)"
                           :action="uploadAction" :show-file-list="false"
                           :on-success="handleAvatarSuccess"
                           :before-upload="beforeAvatarUpload">
                  <img v-if="category.imageUrl" :src="category.imageUrl" class="category-image" />
                  <i v-else class="el-icon-plus category-uploader-icon"></i>
                  <p class="update" slot="trigger"><span>修改</span></p>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="15">
              <el-col :span="24" class="name">{{category.name}}</el-col>
              <el-col :span="24">
                <span>排序:</span>
                <el-input-number  v-model="category.showOrder" @click.native.stop="onFocus(category)" @change="onSortChange" :controls="false" :min="1" :max="99"  size="mini" style="width:60px"></el-input-number>
              </el-col>
            </el-col>
          </div>
        </el-popover>
      </li>
    </ul>
  </section>
</template>

<script>
  import { getUploadFileRequest } from "../../../api";
  import {getBookListByCondition,updateBookSort} from "../../../api/book";

  export default {
    name: "CategoryList",
    props:{
      categorys:{
        type:Array,
        default:[]
      }
    },
    components:{  },
    data(){
      return{
        categoryList:[],
        uploadIndex:-1,
        uploadAction:getUploadFileRequest(),
        isBookListLoading:false,
        bookList:[],
      }
    },
    watch:{
      categoryList:function (value,oldValue) {
        this.autoUpdate();
      }
    },
    methods: {
      onFocus(category){
        category.visible = false;
      },
      onShowBook(category,index){
        if(category.visible) {
          this.categoryList.map(m=>{ if(m.id != category.id) m.visible = false});
          this.loadBookList(category.bookCategoryId);
        }
      },
      async loadBookList(categoryId){
        this.isBookListLoading = true;
        let params = {
          categoryId:categoryId,
          isDraft:0,
          status:1,
        }
        let resp = await getBookListByCondition(params);
        console.log("books==>",resp)
        if(this.qUtil.validResp(resp)){
          this.bookList = resp.data.dataList;
        }else this.$message({ message: resp.msg, type: 'warning' });
        this.isBookListLoading = false;
      },
      onSortChange(){
        this.$nextTick(()=>{
          this.categoryList.sort((a,b)=>{ return a.showOrder - b.showOrder})
        });

      },
      async onBookSortChange(book){
        this.isBookListLoading = true;
        let resp = await updateBookSort({id:book.id,showOrder:book.showOrder});
        if(this.qUtil.validResp(resp)){
          await this.loadBookList(book.categoryId);
        }else this.$message({ message: resp.msg, type: 'warning' });
        this.isBookListLoading = false;
      },
      onUpClick(index){
        this.uploadIndex = index;
      },
      handleAvatarSuccess(res, file) {
        this.categoryList[this.uploadIndex].imageUrl = res.data;//URL.createObjectURL(file.raw);
        this.uploadIndex = -1;
        this.autoUpdate();
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt500KB = file.size / 1024  < 500;
        if (!isJPG && !isPNG) {
          this.$message.error('分类图片只能是 JPG、PNG 格式!');
        }
        if (!isLt500KB) {
          this.$message.error('分类图片大小不能超过 500KB!');
        }
        let isOk = (isJPG||isPNG) && isLt500KB;
        if(!isOk) this.uploadIndex = -1;
        return isOk;
      },
      autoUpdate(){
        this.$emit("update:categorys",this.categoryList)
      }
    },
    mounted(){
      let categoryList = this.baseUtil.modelCopy(this.categorys)
      this.categoryList = categoryList;
    }
  }
</script>

<style scoped>
  .template-categorylist .head{
    margin:0;
    padding:0;
    font-size: 14px;
  }
  .template-categorylist ul,.template-categorylist li{ list-style:none; margin:0;padding:0;}
  .template-categorylist li.category-item{
    cursor: pointer;
    font-size: 14px;
    color:#222222;
    line-height: 160%;
    padding:10px;
    border-bottom:1px solid #f2f2f2;
  }
  .template-categorylist li.category-item.is-active{
    background-color: #F2F2F2;
  }
  .category-item .category-img-box{
    position: relative;
    width:82px;
    height:82px;
    overflow: hidden;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
  }
  .category-item .update{
    position: absolute;
    left:0;
    bottom:0;
    z-index: 10;
    margin:0;
    padding:0;
    width:100%;
    height:20px;
    line-height: 20px;
    background-color: #000;
    cursor: pointer;
    color:#fff;
    font-size: 14px;
    opacity: 0.7;
  }
  .category-uploader{
    margin-bottom:16px;
  }
  .category-uploader-icon {
    margin:0 auto;
    font-size: 30px;
    color: #8c939d;
    text-align: center;
    line-height: 72px;
  }
  .category-image {
    width:80px;
    height:80px;
  }
  .category-item .name{
    padding:10px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .book-table .book-img{
    width:52px;
    height:76px;
    padding:1px;
    float: left;
    border:1px solid #f2f2f2;
    margin-right: 10px;
  }
  .book-table .book-tit,.book-table .book-author{
    margin:0;
    padding: 0;
    line-height: 150%;
    font-size:14px;
  }
  .book-table .book-tit{
    color:#2C2B2A;
    font-weight:bolder;
    padding-bottom:7px;
  }
  .book-table .book-author{
    color:#8D8D8D;
    padding-bottom:7px;
  }
</style>
